/*
 * Copyright (c) TD-Tech Technologies Co., Ltd. 2024-2024. All rights reserved.
 */
import { LogDomain, LogHelper } from './LogHelper';
import { AsyncCallback, BusinessError } from '@ohos.base';
import commonEventManager from '@ohos.commonEventManager';

const TAG = 'systemmanager_CommonEventHelper : ';

const LogUtil: LogHelper = LogHelper.getLogHelper(LogDomain.TdSystemManager, TAG);

/**
 * 公共事件工具类
 *
 * @since 2024-07-25
 */
export class CommonEventHelper {
  /**
   * 订阅者
   */
  public subscriber?: commonEventManager.CommonEventSubscriber;
  /**
   * 订阅者信息
   */
  public subscribeInfo?: commonEventManager.CommonEventSubscribeInfo;
  /**
   * 事件回调
   */
  public subscribeCallBack?: AsyncCallback<commonEventManager.CommonEventData>;
  private isRegister: boolean = false;

  constructor(subscribeInfo: commonEventManager.CommonEventSubscribeInfo, subscribeCallBack:
    AsyncCallback<commonEventManager.CommonEventData>) {
    this.subscribeInfo = subscribeInfo;
    this.subscribeCallBack = subscribeCallBack;
  }

  /**
   * 取消订阅公共事件回调
   */
  private unsubscribeCallBack = (err: BusinessError) => {
    if (err.code) {
      LogUtil.showInfo(`${TAG} unsubscribe failed ${JSON.stringify(err)}`);
    } else {
      LogUtil.showInfo(`${TAG} unsubscribe success`);
    }
  }
  /**
   * 创建订阅者回调
   */
  private createSubscriberCallBack = (err: BusinessError, commonEventSubscriber:
    commonEventManager.CommonEventSubscriber) => {
    if (err) {
      LogUtil.showError(`${TAG} createSubscriber failed. Code is ${err.code}, message is ${err.message}`);
    } else {
      LogUtil.showInfo(`${TAG} createSubscriber success`);
      this.subscriber = commonEventSubscriber;
      //订阅公共事件回调
      commonEventManager.subscribe(this.subscriber, this.subscribeCallBack);
    }
  }

  registerCommonEvent(): void {
    if (this.isRegister) {
      LogUtil.showInfo(`${TAG} already register common event`);
      return;
    }
    commonEventManager.createSubscriber(this.subscribeInfo, this.createSubscriberCallBack);
    this.isRegister = true;
  }

  unRegisterCommonEvent(): void {
    if (!this.isRegister) {
      LogUtil.showInfo(`${TAG} already unregister common event`);
      return;
    }
    commonEventManager.unsubscribe(this.subscriber, this.unsubscribeCallBack);
    this.isRegister = false;
  }

}